# -*- coding:UTF-8 -*-
#! /usr/bin/python

import random
import sys

order = 4

start = [[0] * order for x in range(order)]
process = start

def display(process,score = 0):#显示界面
    global order
    for i in range(order):
        for j in range(order):
            print(process[i][j],'\t',end='')
        print()
    print('total score = ',score)

def init(start):#随机分布初始值
    global order
    for i in range(order):
        start[i] = [random.choice([0,0,0,2,2,4]) for x in start[i]]

def align(process,direction):#对齐，例如[0,8,0,2]-->[0,0,8,2]
    count = process.count(0)
    for i in range(count):
        process.remove(0)
    if direction == 'right':
        process[:0] = [0] * count
    else:
        process.extend([0] * count)

def addSame(process,direction):
    score = 0
    global order
    if direction == 'right':
        for i in [(order - 2 - x) for x in range(order - 1)]:
            if process[i] == process[i+1] != 0:
                process[i] *= 2
                process[i+1] = 0
                score += process[i]
                return {'bool':True,'score':score}
    else:
        for i in range(order - 1):
            if process[i] == process[i+1] != 0:
                process[i+1] *= 2
                process[i] = 0
                score += process[i+1]
                return {'bool':True,'score':score}
    return {'bool':False,'score':score}

def handle(process,direction):
    totalScore = 0
    global order
    align(process,direction)
    result = addSame(process,direction)
    while result['bool']:
        totalScore += result['score']
        result = addSame(process,direction)
    align(process,direction)
    return totalScore

def T(process):#转置矩阵
    global order
    processChange = list(process)
    for i in range(order):
        process[i] = [processChange[j][i] for j in range(order)]

def operation(process):#根据方向操控矩阵
    totalScore = 0
    gameOver = False
    direction = 'right'

    op = input('operator:')

    if op in ['d','D']:
        direction = 'right'
        for i in range(order):
            totalScore += handle(process[i],direction)
    elif op in ['a','A']:
        direction = 'left'
        for i in range(order):
            totalScore += handle(process[i],direction)
    elif op in ['s','S']:
        direction = 'right'
        T(process)
        for i in range(order):
            totalScore += handle(process[i],direction)
        T(process)
    elif op in ['w','W']:
        direction = 'left'
        T(process)
        for i in range(order):
            totalScore += handle(process[i],direction)
        T(process)

    N = 0
    for i in process:
        N += i.count(0)
    if N == 0:
        gameOver = 'True'
        return {'gameOver':gameOver,'score':totalScore}
    
    num = random.choice([2,2,2,4])
    k = random.randrange(1,N+1)
    n = 0
    for i in range(order):
        for j in range(order):
            if process[i][j] == 0:
                n += 1
                if n == k:
                    process[i][j] = num
                    break
    
    return {'gameOver':gameOver,'score':totalScore}


init(process)
totalScore = 0

print('Input：W(Up) S(Down) A(Left) D(Right), press <CR>.')

while True:
    display(process,totalScore)
    result = operation(process)
    if result['gameOver']:
        print('game over')
        print('your score:',totalScore)
        sys.exit(1)
    else:
        totalScore += result['score']
        if totalScore >= 2048:
            print('Game Over, You Win!!!')
            print('Your total score:', totalScore)
            sys.exit(0)

#operation(process)